// components/GaodeInputTips/GaodeInputTips.js
var amapFile = require('../../libs/amap-wx.js');
var config = require('../../libs/config.js');

Component({
  properties: {
    city: {
      type: String,
      value: ''
    },
    longitude: {
      type: String,
      value: ''
    },
    latitude: {
      type: String,
      value: ''
    },
    inputType: {
      type: String,
      value: ''
    },
    defaultValue: {
      type: String,
      value: '请输入'
    }
  },

  data: {
    tips: [],
    tipsShow: false
  },

  lifetimes: {
    attached() {
      // 初始化 lonlat 和 city
      this.lonlat = this.properties.longitude + ',' + this.properties.latitude;
      this.city = this.properties.city;
    },
    ready() {
      const that = this;
      const defaultValue = this.properties.defaultValue;

      // 如果 defaultValue 存在且不是 placeholder，则自动搜索
      if (defaultValue && defaultValue !== '请输入' && defaultValue !== '目的地') {
        const fakeEvent = {
          detail: {
            value: defaultValue,
            autoTrigger: true
          }
        };

        // 调用 bindInput 方法开始搜索
        this.bindInput(fakeEvent);
      }
    }
  },

  methods: {
    bindInput(e) {
      var that = this;
      var keywords = e.detail.value;

      if (keywords === '') {
        that.setData({ tips: [] });
        return false;
      }

      var key = config.Config.key;
      var myAmapFun = new amapFile.AMapWX({ key: key });

      myAmapFun.getInputtips({
        keywords: keywords,
        location: that.lonlat,
        city: that.city,
        success: function(data) {
          if (data && data.tips && data.tips.length > 0) {
            that.setData({ tips: data.tips });

            // 如果是自动触发，就直接选第一个结果并触发 customEvent
            if (e.detail.autoTrigger) {
              const firstResult = data.tips[0];
              that.triggerEvent('customEvent', {
                info: firstResult,
                inputType: that.properties.inputType
              });
            }
          }
        },
        fail: function(err) {
          console.log('搜索失败', err);
        }
      });
    },

    bindSearch(e) {
      this.triggerEvent('customEvent', {
        info: e.target.dataset.info,
        inputType: this.properties.inputType
      });
    },

    handleFocus(e) {
      this.setData({ tipsShow: true });
    },

    handleBlur(e) {
      setTimeout(() => {
        this.setData({ tipsShow: false });
      }, 200);
    }
  }
});